package com.GLM.Viewer.Friends;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.FriendsSMSEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FriendsSMSDetailActivity extends Activity {
	private final static int SMSLIST_LOADING = 111;
	private final static int SMSLIST_LONDED = 222;
	
	View mInputFieldMoreLines;
	EditText mInputFieldMoreLinesEditText;

	Animation mAnimIn;
	Animation mAnimOut;
	InputMethodManager imm;
	
	private ListView mSMSList;
	private SimpleAdapter mSMSAdapter;
	private List<Map<String, Object>> mSMSItems = new ArrayList<Map<String, Object>>();
	private String[] SMSItemKeys = new String[] { "smsDate", "smsWho", "smsContent" };
	private int[] SMSItemIds = new int[] { R.id.friends_sms_date, R.id.friends_sms_who, R.id.friends_sms_content };
	private int talkId;
	private int userId;
	private Map<Integer, Integer> smsTalkMap = new HashMap<Integer, Integer>();
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case SMSLIST_LOADING:
				mSMSItems.clear();
				mSMSAdapter = null;
				thread = new Thread(new Runnable() {
					public void run() {
						initSMSList();
						mSMSAdapter = new SimpleAdapter(FriendsSMSDetailActivity.this, mSMSItems, R.layout.view_friends_smsdetail_item, SMSItemKeys, SMSItemIds);
						mHandler.sendEmptyMessage(SMSLIST_LONDED);
					}

				});
				thread.start();
				break;

			case SMSLIST_LONDED:
				if (mSMSAdapter != null) {
					mSMSList.setAdapter(mSMSAdapter);
					mSMSList.setOnScrollListener(onScrollListener);
				}
				break;
			}
		};
	};

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_friends_smsdetail);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		mSMSList = (ListView)findViewById(R.id.friends_sms_listView);
		userId = UserInfoDAO.getUserInfo(FriendsSMSDetailActivity.this).getUserId();
		Intent intent = getIntent();
		talkId = intent.getIntExtra("talkId", -1);
		initViews();
		initInputFields();
		initAnimation();
		initRegisterInputFieldButton();
		mHandler.sendEmptyMessage(SMSLIST_LOADING);
	}
	
	
	private void initInputFields() {

		mInputFieldMoreLines = findViewById(R.id.inputfield_moreline);
		mInputFieldMoreLines.setVisibility(View.GONE);
		mInputFieldMoreLinesEditText = (EditText) findViewById(R.id.inputfieldmoreline_edittext);
	}
	
	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}
	
	private void showMoreLinesInputField() {
		mInputFieldMoreLines.startAnimation(mAnimIn);
		mInputFieldMoreLines.setVisibility(View.VISIBLE);
		mInputFieldMoreLinesEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	private void hideMoreLinesInputField() {
		mInputFieldMoreLinesEditText.setText("");
		mInputFieldMoreLinesEditText.clearFocus();
		mInputFieldMoreLines.startAnimation(mAnimOut);
		mInputFieldMoreLines.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	
	private void initRegisterInputFieldButton() {
		// more liness
		Button inputMoreLineCancelButton = (Button) findViewById(R.id.inputfieldmoreline_cancelbutton);
		inputMoreLineCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideMoreLinesInputField();
			}
		});

		Button inputMoreLineOkButton = (Button) findViewById(R.id.inputfieldmoreline_okbutton);
		inputMoreLineOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String smsContent = mInputFieldMoreLinesEditText.getText().toString().trim();
				if(smsContent != null){
					hideMoreLinesInputField();
					initSendSMS(smsContent);
				}
			}
		});
	}
	
	public void initViews(){
		Button sendSMSBtn = (Button)findViewById(R.id.friends_SendSMS_Button);
		sendSMSBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showMoreLinesInputField();
			}
		});
	}
	
	
	public void initSMSList(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID, userId);
			jsonData.put(Constant.PARAM_SMS_RECID, talkId);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDSSMSTALK, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_FRIENDS_SMS);

					initSMSItemFromJson(jsonArray);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	
	private OnScrollListener onScrollListener = new OnScrollListener() {
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			LoadSMSItem();
		}
	};
	
	public void initSendSMS(String smsContent){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_SMSCONTENT, smsContent);
			jsonData.put(Constant.PARAM_SMS_SENDUSERID, userId);
			jsonData.put(Constant.PARAM_SMS_RECUSERID, talkId);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_SENDSMS, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == 1) {
					mHandler.sendEmptyMessage(SMSLIST_LOADING);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	
	public void LoadSMSItem(){
		int count = mSMSList.getChildCount();
		for(int i=0; i<count; i++){
			View view = mSMSList.getChildAt(i);
			TextView tvNameView = (TextView)view.findViewById(R.id.friends_sms_who);
			TextView tvContentView = (TextView)view.findViewById(R.id.friends_sms_content);
			int sendId = smsTalkMap.get(i);
			LinearLayout layout = (LinearLayout)view.findViewById(R.id.sms_item_layout);
			if(sendId == userId){
				tvNameView.setText("Me");
				tvNameView.setTextColor(Color.BLUE);
				tvContentView.setTextColor(Color.BLUE);
				
				layout.setGravity(Gravity.RIGHT);
			}
			else {
				layout.setGravity(Gravity.LEFT);
				
			}
			
		}
	}
	
	public void initSMSItemFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			FriendsSMSEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), FriendsSMSEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("smsDate", entity.getSms_date());
			item.put("smsWho", entity.getSender_nickname());
			item.put("smsContent", entity.getSms_content());
			Log.d("friends_sms", entity.getSms_date()+">>"+entity.getSender_nickname()+">>"+entity.getSms_content());
			
			mSMSItems.add(item);
			smsTalkMap.put(i, entity.getSms_send_user_id());
		}
	}
	
	public void goBackButton_OnClick(View v){
		NavUtils.navigateUpFromSameTask(FriendsSMSDetailActivity.this);
	}
}
